package com.czk.api.putData;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/2 15:55
 */
public class PutData {
    private static Connection connection = null;
    private static Admin admin = null;

    static {
        // 静态代码块初始化
        // 创建配置类
        Configuration configuration = HBaseConfiguration.create();
        // zookeeper连接
        configuration.set("hbase.zookeeper.quorum", "192.168.25.133");
        // 端口
        configuration.set("hbase.zookeeper.property.clientPort", "2181");
        //
        try {
            connection = ConnectionFactory.createConnection(configuration);
            admin = connection.getAdmin();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    public static void close() {
        try {
            if (admin != null) {
                admin.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException {
        putData("stu", "1001", "info1", "name", "czk");
    }

    /**
     * 存数据
     *
     * @param tableName 表名称
     * @param rowKey    住建
     * @param cf        列族
     * @param cn        列名
     * @param value     值
     * @throws IOException
     */
    public static void putData(String tableName, String rowKey, String cf, String cn, String value) throws IOException {
        // 拿到表对象
        Table table = connection.getTable(TableName.valueOf(tableName));
        // 创建put对象
        Put put = new Put(Bytes.toBytes(rowKey));
        // 给put对象赋值
        put.addColumn(Bytes.toBytes(cf), Bytes.toBytes(cn), Bytes.toBytes(value));
        // 插入数据
        table.put(put);
        // 关闭资源
        close();
    }
}
